<template>
  <div id="userRegister">
    <h2 style="margin-bottom: 20px;">用户注册</h2>
    <a-form :model="form" ref="formRef" :style="{ width: '100%' }" @submit="handleSubmit" :rules="rules">
      <!-- 账号 -->
      <a-form-item tooltip="账号不能小于4位" field="userAccount" label="账号:" :validate-trigger="['input','blur']">
        <a-input
          v-model="form.userAccount"
          placeholder="请输入账号..."
        />
      </a-form-item>

      <!-- 密码 -->
      <a-form-item field="userPassword"  tooltip="密码不能小于8位" label="密码:" :validate-trigger="['input','blur']">
        <a-input-password v-model="form.userPassword" placeholder="请输入密码..." />
      </a-form-item>

      <!-- 确认密码 -->
      <a-form-item field="checkPassword"  tooltip="输入的密码要与密码一致" label="确认密码:" :validate-trigger="['input','blur']">
        <a-input-password v-model="form.checkPassword" placeholder="请再次输入密码..." />
      </a-form-item>

      <!-- 注册   -->
      <a-form-item>
        <div style="width: 100%;display: flex;align-items: center;justify-content: space-between;">
          <a-button  type="primary" style="width:50%" html-type="submit">注册</a-button>
          <router-link style="text-decoration: none;" to="/user/login">->去登录</router-link>
        </div>
      </a-form-item>
      
    </a-form>
  </div>
  
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import API from '@/api'
import {  userRegisterUsingPost } from '@/api/userController';
import { useLoginUserStore } from '@/store/userStore';
import message from '@arco-design/web-vue/es/message'
import { useRouter } from 'vue-router';

const router = useRouter();


const loginUserStore = useLoginUserStore();

// 定义表单数据
const form = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: ''
} as API.UserRegisterRequest);

// 定义校验规则
const rules = {
  userAccount: [
    { required: true, message: '账号不能为空' },
    {minLength:4, message: '账号长度不能小于4位' }
  ],
  userPassword: [
    { required: true, message: '密码不能为空' },
    {minLength:8, message: '密码长度不能小于8位'}
  ],
  checkPassword: [
    {
      required: true,
      message:'二次密码不能为空',
    },
    {
      validator: (value:any, cb:any) => {
        if (value !== form.userPassword) {
          cb('前后密码输入不一致~')
        } else {
          cb()
        }
      }
    }
  ]
}


// 提交表单
const handleSubmit = async ({value, errors}:any) => {
  if(!errors) {
    const res = await userRegisterUsingPost(form)
    if(res.data.code === 0) {
      // 获取用户信息
      await loginUserStore.fetchLoginUser()
      message.success('注册成功')
      router.replace({ path: '/user/login' })
    } else {
      message.error('注册失败:' + res.data.message as string)
    }
  }
}

</script>
<style lang="scss" scoped>
#userRegister {
  width: 40vw;
  padding: 20px;
  border-radius: 10px;
  background: rgba(255,255,255,.6);
  margin: 0 auto;
  min-width: 400px;
}
</style>